import React, { Component } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi/locale';
import { Alert, Button, Checkbox, Col, Divider, Form, Input, Row, Icon, AutoComplete } from 'antd';
import * as CryptoJS from 'crypto-js';
import { routerRedux } from 'dva/router';
import Modal from 'drag-modal';
import PropTypes from 'prop-types';
import fetch from 'dva/fetch';
import Login from '@/components/Login';
import { isFakeData } from '@/utils/utils';
import styles from './Login.less';
import { getWebPath } from '../../utils/request';
import uiUtils, { rulesReg, rulesRemote } from '../../utils/uiUtils';
import { requestLists, requestPromise } from '@/utils/request';

const FormItem = Form.Item;
const { Tab, UserName, Password, Mobile, Captcha, Submit } = Login;
let countDown = 60;
let password = '';
let repeatPassword = '';
@connect(({ login, loading }) => ({
  login,
  submitting: loading.effects['login/login'],
}))
class LoginPage extends Component {
  state = {
    type: 'account',
    autoLogin: true,
    src: getWebPath(`/captcha.jpg?t=${Math.random()}`),
  };

  onTabChange = type => {
    this.setState({ type });
  };

  onGetCaptcha = () =>
    new Promise((resolve, reject) => {
      this.loginForm.validateFields(['mobile'], {}, (err, values) => {
        if (err) {
          reject(err);
        } else {
          const { dispatch } = this.props;
          dispatch({
            type: 'login/getCaptcha',
            payload: values.mobile,
          })
            .then(resolve)
            .catch(reject);
        }
      });
    });

  onGetImgCaptcha = () => {
    this.setState({
      src: getWebPath(`/captcha.jpg?t=${Math.random()}`),
    });
  };

  handleSubmit = (err, values) => {
    console.log('登录事件跟踪-step:001');
    if (!isFakeData()) {
      values.password = this.encryptByDES(values.password, 'DES_KEY_PASSWORD');
    } else {
      values.userName = values.username;
    }

    const { type } = this.state;
    if (!err) {
      const { dispatch } = this.props;
      const data = {
        parentMethod: this,
        values,
      };
      dispatch({
        type: 'login/login',
        payload: {
          ...data,
          type,
        },
      });
      // eslint-disable-next-line no-prototype-builtins
    } else if (
      this.props.login.isShowCaptcha === false &&
      // eslint-disable-next-line no-prototype-builtins
      err.hasOwnProperty('captcha') &&
      // eslint-disable-next-line no-prototype-builtins
      !err.hasOwnProperty('password') &&
      // eslint-disable-next-line no-prototype-builtins
      !err.hasOwnProperty('username')
    ) {
      //由于第一次进来，验证码input框是存在代码当中，只不过是不显示，保存的时候依然会报验证码必填的错，所以在这儿需对这种情况特殊处理
      const { dispatch } = this.props;
      const data = {
        parentMethod: this,
        values,
      };
      dispatch({
        type: 'login/login',
        payload: {
          ...data,
          type,
        },
      });
    }
  };

  showModal = () => {
    this.props.dispatch(routerRedux.push({
      pathname: '/user/reset-password'
    }));
  };

  changeAutoLogin = e => {
    this.setState({
      autoLogin: e.target.checked,
    });
  };

  renderMessage = content => (
    <Alert style={{ marginBottom: 24 }} message={content} type="error" showIcon />
  );

  encryptByDES = (message, key) => {
    const keyHex = CryptoJS.enc.Utf8.parse(key);
    const encrypted = CryptoJS.DES.encrypt(message, keyHex, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    return encrypted.toString();
  };

  render() {
    const { login, submitting } = this.props;
    const { type, autoLogin } = this.state;

    return (
      <div className={styles.main}>
        <Login
          defaultActiveKey={type}
          onTabChange={this.onTabChange}
          onSubmit={this.handleSubmit}
          ref={form => {
            this.loginForm = form;
          }}
        >
          <Tab key="account" tab={formatMessage({ id: 'app.login.welcome' })}>
            {(login.code === 900001 || login.code === 500) &&
              // login.type === 'account' &&
              !submitting &&
              this.renderMessage(
                login.msg || formatMessage({ id: 'app.login.message-invalid-credentials' })
              )}
            <UserName
              name="username"
              placeholder={`${formatMessage({ id: 'app.login.userName' })}`}
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'validation.userName.required' }),
                },
              ]}
            />
            <Password
              name="password"
              placeholder={`${formatMessage({ id: 'app.login.password' })}`}
              rules={[
                {
                  required: true,
                  message: formatMessage({ id: 'validation.password.required' }),
                },
              ]}
              onPressEnter={() => this.loginForm.validateFields(this.handleSubmit)}
            />
            <div hidden={login.isShowCaptcha === false}>
              <Captcha
                name="captcha"
                countDown={3}
                placeholder={formatMessage({ id: 'form.verification-code.placeholder' })}
                onGetCaptcha={this.onGetImgCaptcha}
                getCaptchaButtonText={formatMessage({ id: 'form.get-captcha' })}
                getCaptchaSecondText={formatMessage({ id: 'form.captcha.second' })}
                rules={[
                  {
                    required: true,
                    message: formatMessage({ id: 'validation.verification-code.required' }),
                  },
                ]}
              />
              {/* eslint-disable-next-line jsx-a11y/alt-text */}
              <img src={this.state.src} onClick={this.onGetImgCaptcha} />
            </div>
          </Tab>
          {/*手机号登录*/}
          {/*<Tab key="mobile" tab={formatMessage({ id: 'app.login.tab-login-mobile' })}>*/}
          {/*{login.status === 'error' &&*/}
          {/*login.type === 'mobile' &&*/}
          {/*!submitting &&*/}
          {/*this.renderMessage(*/}
          {/*formatMessage({ id: 'app.login.message-invalid-verification-code' })*/}
          {/*)}*/}
          {/*<Mobile*/}
          {/*name="mobile"*/}
          {/*placeholder={formatMessage({ id: 'form.phone-number.placeholder' })}*/}
          {/*rules={[*/}
          {/*{*/}
          {/*required: true,*/}
          {/*message: formatMessage({ id: 'validation.phone-number.required' }),*/}
          {/*},*/}
          {/*{*/}
          {/*pattern: /^1\d{10}$/,*/}
          {/*message: formatMessage({ id: 'validation.phone-number.wrong-format' }),*/}
          {/*},*/}
          {/*]}*/}
          {/*/>*/}
          {/* <Captcha
            name="captcha"
            placeholder={formatMessage({id: 'form.verification-code.placeholder'})}
            countDown={120}
            onGetCaptcha={this.onGetCaptcha}
            getCaptchaButtonText={formatMessage({id: 'form.get-captcha'})}
            getCaptchaSecondText={formatMessage({id: 'form.captcha.second'})}
            rules={[
              {
                required: true,
                message: formatMessage({id: 'validation.verification-code.required'}),
              },
            ]}
          />*/}
          {/*</Tab>*/}
          {/*忘记密码*/}
          {/*<div>*/}
          {/*<Checkbox checked={autoLogin} onChange={this.changeAutoLogin}>*/}
          {/*<FormattedMessage id="app.login.remember-me" />*/}
          {/*</Checkbox>*/}
          {/*<a style={{ float: 'right' }} href="">*/}
          {/*<FormattedMessage id="app.login.forgot-password" />*/}
          {/*</a>*/}
          {/*</div>*/}
          <Submit loading={submitting}>
            <FormattedMessage id="app.login.login" />
          </Submit>
          <div style={{ textAlign: 'center' }}>
            <a onClick={this.showModal}>
              <FormattedMessage id="app.login.forgetPsd" />
            </a>
          </div>
          {/*其他登录方式*/}
          {/*<div className={styles.other}>*/}
          {/*<FormattedMessage id="app.login.sign-in-with" />*/}
          {/*<Icon type="alipay-circle" className={styles.icon} theme="outlined" />*/}
          {/*<Icon type="taobao-circle" className={styles.icon} theme="outlined" />*/}
          {/*<Icon type="weibo-circle" className={styles.icon} theme="outlined" />*/}
          {/*<Link className={styles.register} to="/user/register">*/}
          {/*<FormattedMessage id="app.login.signup" />*/}
          {/*</Link>*/}
          {/*</div>*/}
        </Login>
        <EditForm
          visible={this.state.visible}
          cancel={() => {
            this.setState({
              visible: false,
            });
          }}
        />
      </div>
    );
  }
}

export default LoginPage;

class EditForm extends React.Component {
  mailSuffix = ['163.com', '126.com', 'gmail.com', 'qq.com', 'hotmail.com', 'sohu.com', 'sina.com'];

  static propTypes = {
    visible: PropTypes.string,
    // eslint-disable-next-line react/require-default-props
    cancel: PropTypes.func,
  };

  static defaultProps = {
    visible: '',
  };

  constructor(props) {
    super(props);
    this.state = {
      btnName: '获取验证码',
    };
  }

  handleOk = () => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const info = this.props.form.getFieldsValue();
        requestPromise(`${getWebPath(`sys/user/forgetPsd`)}`, {
          method: 'post',
          body: JSON.stringify(info),
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
        }).then(res => {
          if (res.code === 0) {
            uiUtils.showMessage('修改成功,请重新登陆', 'success');
            console.log(this);
            // eslint-disable-next-line no-unused-expressions
            this.props.cancel();
          }
        });
      }
    });
  };

  //获取验证码
  getCheckCode = () => {
    this.setState({ loading: true });
    const email = this.state.email;

    requestPromise(`${getWebPath(`sys/user/sendCheckCodeForForgetPsw?email=${email}`)}`, {
      method: 'get',
    }).then(res => {
      if (res.code === 0) {
        this.countDown();
      }
    });
  };

  //倒计时
  countDown = () => {
    countDown -= 1;
    if (countDown === 0) {
      this.setState({
        btnName: '获取验证码',
        loading: false,
      });
      countDown = 60;
    } else {
      this.setState({ btnName: `${countDown}s后重新获取` });
      setTimeout(this.countDown, 1000);
    }
  };

  //判断两次密码是否一致
  checkConfirm = (rule, value, callback) => {
    if (password.trim() !== '' && repeatPassword.trim() !== '') {
      if (password !== repeatPassword) {
        return callback('两次密码不一致!');
      }
    }
    return callback();
  };

  autoCompleteHandleSearch = value => {
    this.setState({
      mailDataSource:
        !value || value.indexOf('@') === -1
          ? []
          : this.mailSuffix
              .map(en => `${value.split('@', 2)[0]}@${en}`)
              .filter(en => en.indexOf(value.split('@', 2)[1]) !== -1),
    });
  };

  render() {
    const colSpanLayout = { md: 21, sm: 21 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 24 }; //col之间的间隔?px
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 17 }, //5+19=24,少一个栅格
    };
    const { getFieldDecorator } = this.props.form;

    return (
      <Modal
        title="修改密码"
        visible={this.props.visible}
        onOk={this.handleOk}
        onCancel={this.props.cancel}
        width={600}
        okText="提交"
        cancelText="取消"
        destroyOnClose="true"
      >
        <Form layout="horizontal">
          <Row gutter={{ ...rowGutterPxLayout }}>
            <Col {...colSpanLayout}>
              <FormItem label="邮箱：" {...formItemLayout}>
                {getFieldDecorator('email', {
                  rules: [
                    {
                      required: true,
                      message: '必填',
                    },
                    rulesReg('email'),
                  ],
                })(
                  <AutoComplete
                    type="text"
                    maxLength={50}
                    placeholder=""
                    autocomplete="off"
                    dataSource={this.state.mailDataSource}
                    onSearch={this.autoCompleteHandleSearch}
                    onBlur={value => {
                      this.setState({
                        email: value,
                      });
                    }}
                  />
                )}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="验证码：" {...formItemLayout}>
                {getFieldDecorator('checkCode', {
                  rules: [
                    rulesReg('digits'),
                    rulesRemote('POST', getWebPath('sys/user/checkEmailCode'), {
                      email: this.state.email,
                    }),
                  ],
                  validateTrigger: 'onBlur',
                })(
                  <Input
                    type="text"
                    maxLength={10}
                    placeholder=""
                    style={{ width: 100 }}
                    autocomplete="off"
                  />
                )}
                <Icon type={this.state.tureOrFalse} style={{ marginLeft: 20, fontSize: 20 }} />
                <Button
                  type="primary"
                  style={{ float: 'right' }}
                  loading={this.state.loading}
                  onClick={this.getCheckCode}
                >
                  {this.state.btnName}
                </Button>
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="新密码：" {...formItemLayout}>
                {getFieldDecorator('password', {
                  rules: [
                    {
                      required: true,
                      message: '必填',
                    },
                    { validator: this.checkConfirm },
                  ],
                  validateTrigger: 'onBlur',
                })(
                  <Input.Password
                    type="text"
                    maxLength={50}
                    placeholder=""
                    autocomplete="off"
                    onBlur={e => {
                      password = e.target.value;
                    }}
                  />
                )}
              </FormItem>
            </Col>
            <Col {...colSpanLayout}>
              <FormItem label="再次输入密码：" {...formItemLayout}>
                {getFieldDecorator('repeatPassword', {
                  rules: [
                    {
                      required: true,
                      message: '必填',
                    },
                    { validator: this.checkConfirm },
                  ],
                  validateTrigger: 'onBlur',
                })(
                  <Input.Password
                    type="text"
                    maxLength={50}
                    placeholder=""
                    autocomplete="off"
                    onBlur={e => {
                      repeatPassword = e.target.value;
                    }}
                  />
                )}
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Modal>
    );
  }
}
// eslint-disable-next-line no-class-assign
EditForm = Form.create({})(EditForm);
